var fs = require('fs');
var path = require('path');
const os = require('os');
var webpack = require('webpack');
const HappyPack = require('happypack');
const lessToJs = require('less-vars-to-js');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPluginProduction = require('html-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin-for-multihtml');
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');    //压缩插件
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');//打包内容分析
// 二次构建优化
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
//打包进度条
const WebpackBar = require('webpackbar');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');


const ENV = process.env.ENV
const pkgJson = require('./package');
const configObj = pkgJson.config[ENV] || {};
const publicPath = configObj.publicPath;
const CDN_BASE = configObj.CDN_BASE;
const domainName = configObj.domainName;
const OSS_BASE = configObj.OSS_BASE;
const OSS_HOST = configObj.OSS_HOST;
const BACKEND_BASE = configObj.BACKEND_BASE;



// 拿到系统CPU的最大核数，happypack 将编译工作灌满所有线程
const happyThreadPool = ENV == "loc" ? HappyPack.ThreadPool({ size: os.cpus().length }) : HappyPack.ThreadPool({ size: 3 })


//转换 less 变量,用于主题
const baseLess = lessToJs(fs.readFileSync(path.join(__dirname, './src/themes/themes.less'), 'utf8'));
let themers = {};
Object.keys(baseLess).map((k, i) => {
	let key = String(k).replace(/@/g, "");
	themers[key] = String(baseLess[k]);
});

const lessVars = Object.assign(themers, { "@CDN_BASE": JSON.stringify(CDN_BASE) });

process.noDeprecation = true;

const templateHtml = function () {
	return new HtmlWebpackPluginProduction({
		filename: 'index.html',
		favicon: 'src/assets/favicon.ico',
		inject: 'body',  // script标签位于HTML文件的body底部
		showErrors: true,
		CDN_BASE: CDN_BASE,
		OSS_BASE: OSS_BASE,
		OSS_HOST: OSS_HOST,
		publicPath: publicPath,
		domainName: domainName,
		BACKEND_BASE: BACKEND_BASE,
		W_ENV: ENV,
		hash: true,
		template: path.join(__dirname, 'src/index.html')
	})
}

var plugins = [
	new WebpackBar(),
	new ProgressBarPlugin(),
	// 这个插件可以使二次构建速度明显提升
	new HardSourceWebpackPlugin({
		// environmentHash被用来确定这一点。如果散列与先前的构建不同，则将使用新的缓存
		environmentHash: {
			root: process.cwd(),
			directories: [],
			files: ['package-lock.json', 'yarn.lock']
		}
	}),
	new HappyPack({
		id: 'jsx',     // 用唯一的标识符id来代表当前的HappyPack处理一类特定的文件
		threadPool: happyThreadPool,   // 使用多少线程
		loaders: [
			{
				loader: 'babel-loader',
				query: {
					presets: [
						[
							'latest',
							{
								loose: true,
								modules: false,
							},
						],
						'react',
						'es2015',
						'stage-0',
					],
					plugins: [
						'transform-decorators-legacy',
						'transform-class-properties',
						'transform-object-rest-spread',
						['import', { libraryName: 'antd', style: false }],
						[
							'babel-plugin-imports-transform',
							{
								'yx-widget': {
									transform: 'yx-widget/component/${member}',
									preventFullImport: true,
									style: 'yx-widget/component/${member}/index.less',
								},
								'yx-widgetDemo': {
									transform: 'yx-widget/demo/${member}',
									preventFullImport: true,
									style: 'yx-widget/demo/${member}/index.less',
								},
							},
						],
					],
				},
			},
		],
	}),
	new HappyPack({
		id: 'less',
		threadPool: happyThreadPool,
		loaders: [
			{
				loader: 'css-loader',
				options: {
					importLoaders: 1,
					modules: true,
					localIdentName: '[local]___[hash:base64:5]', // 打开混淆
				},
			},
			'postcss-loader',
			{
				loader: 'less-loader',
				options: {
					modifyVars: lessVars,
					javascriptEnabled: true,
				},
			},
		],
	}),
	new HappyPack({
		id: 'less2',
		threadPool: happyThreadPool,
		loaders: [
			{
				loader: 'css-loader',
				options: {
					importLoaders: 1,
					modules: true,
					localIdentName: '[local]',
				},
			},
			'postcss-loader',
			{
				loader: 'less-loader',
				options: {
					modifyVars: lessVars,
					javascriptEnabled: true,
				},
			},
		],
	}),
	new CopyWebpackPlugin([
		{ from: './dll', to: 'dll' },
		{ from: path.resolve(__dirname, './src/assets'), to: 'assets', ignore: ['.*'] },
		{ from: './q9mYvlur7d.txt', to: 'q9mYvlur7d.txt' },
		{ from: './akah3Eegmh.txt', to: 'akah3Eegmh.txt' },
		{ from: './ZLjPbbadGR.txt', to: 'ZLjPbbadGR.txt' },
	]),
	templateHtml(),
	new webpack.DefinePlugin({
		'process.env': {
			NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'prod:dev')
		},
		"ENV": JSON.stringify(ENV || 'dev'),
		"CDN_BASE": JSON.stringify(CDN_BASE || ''),
		"OSS_BASE": JSON.stringify(OSS_BASE || ''),
		"OSS_HOST": JSON.stringify(OSS_HOST || ''),
		"BACKEND_BASE": JSON.stringify(configObj.BACKEND_BASE),
		"publicPath": JSON.stringify(configObj.publicPath),
		"domainName": JSON.stringify(configObj.domainName),
		"LANGUAGES_ENV": JSON.stringify(process.env.LANGUAGES_ENV || 'zhCN'),
	}),
	new webpack.DllReferencePlugin({
		// context: __dirname,
		manifest: require('./dll/manifest.json')
	}),
	//优化打包速度和体积，webpack新插件
	new ExtractTextPlugin('[name].css'),
	//提升模块化的性能
	new webpack.optimize.ModuleConcatenationPlugin(),
]

if (process.env.MOD === 'repost') {
	//打包模块分析
	console.log('查看报告', process.env)
	plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 8919 }))
}

if ('loc' !== '' + ENV) {
	if (['dev', "test"].includes(ENV)) {
		plugins.push(new OpenBrowserPlugin(), new webpack.HotModuleReplacementPlugin())
	} else {
		plugins.push(
			// 压缩插件
			new ParallelUglifyPlugin({
				cacheDir: '.cache/',
				uglifyJS: {
					output: {
						comments: false //去掉注释
					},
					warnings: false,
					compress: {
					}
				}
			})
		)
	}
} else {
	plugins.push(
		new OpenBrowserPlugin({ url: 'http://localhost:3009' }),
		new webpack.HotModuleReplacementPlugin(),
	)
}

module.exports = {
	entry: {
		// 'babel-polyfill': 'babel-polyfill',
		app: [
			'./src/index.js'
		],
	},
	output: {
		filename: `[name].[hash:8].js?time=${Date.now()}`,
		path: path.join(__dirname, 'dist'),
		publicPath: publicPath,
		chunkFilename: `[name].[chunkhash:8].js`
	},
	devtool: 'loc' !== '' + ENV ? false : 'eval-source-map',
	plugins,
	resolve: {
		alias: {
			// "moment": "moment/moment.js",
			pages: path.join(__dirname, 'src/pages'),
			widget: path.join(__dirname, 'src/widget'),
			router: path.join(__dirname, 'src/router'),
			utils: path.join(__dirname, 'src/utils'),
			assets: path.join(__dirname, 'src/assets'),
			themes: path.join(__dirname, 'src/themes'),
			config: path.join(__dirname, 'src/config'),
			"yx-widget": path.join(__dirname, 'src/yx-widget'),
			// "CarSale": path.join(__dirname, 'src/pages/CarSale'), // 整车
			// "ServiceMgmt": path.join(__dirname, 'src/pages/ServiceMgmt'), // 服务
			// "SpareMgmt": path.join(__dirname, 'src/pages/SpareMgmt'), // 备件
			// "SystemSupport": path.join(__dirname, 'src/pages/SystemSupport'), // 系统支持
		},
		modules: [path.join(__dirname, 'src'), 'node_modules'],
		extensions: [".js", ".jsx", '.less', '.css']
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				use: 'happypack/loader?id=jsx',
				include: path.join(__dirname, 'src'),
				exclude: /(node_modules)/
			},
			{
				test: /\.(less|css)$/,
				use: ['style-loader', 'happypack/loader?id=less'],
				exclude: [path.resolve(__dirname, './src/yx-widget')]
			},
			{
				test: /\.(less|css)$/,
				use: ['style-loader', 'happypack/loader?id=less2'],
				include: [path.resolve(__dirname, './src/yx-widget')]
			},
			{
				test: /\.(xml|bpmn)$/,
				use: [{
					loader: 'url-loader',
					options: {
						limit: 1
					}
				}]
			},
			{
				test: /\.(png|jpg|gif|md)$/,
				use: [`file-loader?limit=10000${ENV === 'loc' ? '&name=[md5:hash:base64:10]' : ''}.[ext]`]
			},
			{
				test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
				use: ['url-loader?limit=10000&mimetype=images/svg+xml']
			},
			{
				test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: "url-loader?limit=10000&mimetype=application/font-woff"
			},
			{
				test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: "file-loader"
			},
			{
				test: /\.json$/,
				use: 'json-loader'
			}
		]
	},
	optimization: {
		namedModules: true, //取代插件中的 new webpack.NamedModulesPlugin()
		namedChunks: true,
		runtimeChunk: 'single',
		//splitChunks 默认配置
		splitChunks: {
			chunks: 'async',
			minSize: 30000,
			maxSize: 0,
			minChunks: 1,
			maxAsyncRequests: 5,
			maxInitialRequests: 3,
			automaticNameDelimiter: '~',
			name: true,
			cacheGroups: {
				vendors: {
					test: /[\\/]node_modules[\\/] | [\\/]yx-widget[\\/]/,
					priority: -10
				},
				default: {
					minChunks: 2,
					priority: -20,
					reuseExistingChunk: true
				}
			}
		}
	},
	devServer: { // webpack-dev-server配置热更新以及跨域
		historyApiFallback: true, //不跳转
		noInfo: true,
		inline: true, // 实时刷新
		port: '3009', // 不指定固定端口
		hot: true,
		host: '0.0.0.0',
		// proxy: {
		//   "**": "/",
		//   changeOrigin: true
		// }
		proxy: {
			// 用于地图搜索
			// "/mapApi": {
			//   target: 'https://apis.map.qq.com',
			//   pathRewrite: { '^/mapApi': '' },
			//   changeOrigin: true,     // target是域名的话，需要这个参数，
			//   secure: true,          // 设置支持https协议的代理
			// },
			// "/v1/memberInitiativeLabel": {
			//   target: 'http://192.168.80.75:64222',
			//   pathRewrite: { '^/v1/memberInitiativeLabel': 'v1/memberInitiativeLabel' },
			//   changeOrigin: true,     // target是域名的话，需要这个参数，
			//   secure: true,              // 设置支持https协议的代理
			// },
			// "/v1/label": {
			//   target: 'http://192.168.80.75:64222',
			//   pathRewrite: { '^/v1/label': 'v1/label' },
			//   changeOrigin: true,     // target是域名的话，需要这个参数，
			//   secure: true,              // 设置支持https协议的代理
			// },
			// "/v1/memberLabelGroup": {
			//   target: 'http://192.168.83.194:64222',
			//   pathRewrite: { '^/v1/memberLabelGroup': 'v1/memberLabelGroup' },
			//   changeOrigin: true,     // target是域名的话，需要这个参数，
			//   secure: true,              // 设置支持https协议的代理
			// },
			"/v1/trackStatisticsRest": {
				target: 'http://192.168.83.24:30298/',
				pathRewrite: { '^/v1/trackStatisticsRest': '/v1/trackStatisticsRest' },
				changeOrigin: true,     // target是域名的话，需要这个参数，
				secure: true,              // 设置支持https协议的代理
			},
			"/v1/dash/board": {
				target: 'http://10.222.18.20:30001/',
				pathRewrite: { '^/v1/dash/board': '/v1/dash/board' },
				changeOrigin: true,     // target是域名的话，需要这个参数，
				secure: true,              // 设置支持https协议的代理
			},
			"/v1/carBookPost": {
				target: 'http://192.168.81.111:30298/',
				pathRewrite: { '^/v1/carBookPost': '/v1/carBookPost' },
				changeOrigin: true,     // target是域名的话，需要这个参数，
				secure: true,              // 设置支持https协议的代理
			},
		}
	},
};
